package cn.ytxy.double_system_data_visualization_demo.base.interceptors;

import cn.ytxy.double_system_data_visualization_demo.base.exception.ParamsException;
import cn.ytxy.double_system_data_visualization_demo.base.response.JsonResult;
import cn.ytxy.double_system_data_visualization_demo.base.response.StatusCode;
import cn.ytxy.double_system_data_visualization_demo.user.mapper.UserMapper;
import cn.ytxy.double_system_data_visualization_demo.user.pojo.dto.UserQuery;
import cn.ytxy.double_system_data_visualization_demo.user.pojo.entity.User;
import cn.ytxy.double_system_data_visualization_demo.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        log.debug("token: {}", token);

        if (token == null || !token.contains(" ")) {
            throw new ParamsException(StatusCode.NOT_LOGIN);
        }

        String headerToken = token.split(" ")[1];
        log.debug("headerToken: {}", headerToken);

        try {
            String s = userMapper.selectToken(headerToken);
            if (s == null || s.isEmpty()) {
                throw new ParamsException(StatusCode.NOT_LOGIN);
            }
            // 放行
            return true;
        } catch (ParamsException e) {
            response.setStatus(e.getStatusCode().getCode());
            return false;
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
